using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

[RequireComponent(typeof(Renderer))]    
public class NPC : MonoBehaviour
{
    public float moveRange = 10f; // 移动范围
    public float arrivalThreshold = 0.1f; // 到达阈值

    private Vector3 targetPosition; // 目标位置
    private bool isPause;
    private Color originalColor;
    private Renderer objectRenderer;


    private void Start()
    {
        GenerateRandomPosition();
        objectRenderer = GetComponent<Renderer>();
        originalColor = objectRenderer.material.color;
    }

    private void Update()
    {
        if (isPause) return;
        // 检查是否到达目标位置
        if (Vector3.Distance(transform.position, targetPosition) <= arrivalThreshold)
        {
            GenerateRandomPosition();
        }
        // 平滑地将NPC移动到目标位置
        MoveToPosition(targetPosition);
    }

    private void GenerateRandomPosition()
    {
        // 在初始位置范围之内随机生成一个位置
        float randomX = Random.Range(-moveRange, moveRange);
        float randomZ = Random.Range(-moveRange, moveRange);
        targetPosition = new Vector3(randomX, transform.position.y, randomZ);
    }

    private void MoveToPosition(Vector3 position)
    {
        // 使用线性插值平滑地将NPC移动到目标位置
        float moveSpeed = 5f; // 移动速度
        transform.position = Vector3.MoveTowards(transform.position, position, moveSpeed * Time.deltaTime);
    }
    void OnMouseOver()
    {
        if (Input.GetMouseButtonDown(1))
        {
            StopCoroutine(nameof(ChangeCloreCoroutine));
            StartCoroutine(nameof(ChangeCloreCoroutine));
            Debug.Log("点击一次");
        }
    }


    private void ChangeColor(Color newColor)
    {
        objectRenderer.material.color = newColor;
    }
    IEnumerator ChangeCloreCoroutine()
    {
        isPause=true;
        ChangeColor(Color.blue);
        yield return new WaitForSeconds(3);
        isPause=false;
        ChangeColor(originalColor);
    }
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.CompareTag("Player"))
        {
            Destroy(gameObject);
            GameManager.instance.DestroyNPC();
        }
    }
}
